package org.jfree.chart.demo;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

import org.jfree.base.modules.DefaultModuleInfo;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.time.Millisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;

/**
 * A demonstration application showing a time series chart where you can
 * dynamically add (random) data by clicking on a button.
 * 
 */
public class DynamicDataDemo extends ApplicationFrame {

	/** The time series data. */
	private static TimeSeries series;

	private static Double locLightValue = 0.0;

	/** The most recent value added. */
	private static double lastValue = 100.0;

	/**
	 * Constructs a new demonstration application.
	 * 
	 * @param title
	 *            the frame title.
	 */
	public DynamicDataDemo(final String title) {

		super(title);
		this.series = new TimeSeries(" Light Intensity (cd/m^2)",
				Millisecond.class);
		final TimeSeriesCollection dataset = new TimeSeriesCollection(
				this.series);
		final JFreeChart chart = createChart(dataset);
		final ChartPanel chartPanel = new ChartPanel(chart);
		final JPanel panelMain = new JPanel(new BorderLayout());

		String data[][] = { { "Timestamp", "Sensor Reading" } };

		String col[] = { "Timestamp", "Sensor Reading" };
		
		final DefaultTableModel model = new DefaultTableModel(data, col);

		final JTable table = new JTable(model);
		
		panelMain.add(table,BorderLayout.CENTER);

		final JButton startButton = new JButton("History");
		startButton.setActionCommand("SHOW_DATA");
		startButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				model.setRowCount(1);
//				table.removeAll();
				
				List<SensorDomain> listSensors = Persistance.sensorReading();
				
				Iterator<SensorDomain> itr = listSensors.iterator();
				while (itr.hasNext()) {
					SensorDomain sns = itr.next();
					System.err.println(sns.getTimeStamp() + " : " + sns.getSensorReading());
					model.insertRow(1, new Object[]{ sns.getTimeStamp(), sns.getSensorReading()});
				}
				listSensors.removeAll(listSensors);
			}
		});
		
		final JButton clearButton = new JButton("Clear");
		startButton.setActionCommand("CLEAR_DATA");
		startButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				
				List<SensorDomain> listSensors = Persistance.sensorReading();
				Iterator<SensorDomain> itr = listSensors.iterator();
				while (itr.hasNext()) {
					SensorDomain sns = itr.next();
					System.err.println(sns.getTimeStamp() + " : " + sns.getSensorReading());
					table.removeAll();
					
				}
			}
		});
		

		panelMain.add(chartPanel, BorderLayout.WEST);
		panelMain.add(startButton, BorderLayout.SOUTH);
//		panelMain.add(clearButton);
//		chartPanel.setPreferredSize(new java.awt.Dimension(100, 100));
		setContentPane(panelMain);

	}

	/**
	 * Creates a sample chart.
	 * 
	 * @param dataset
	 *            the dataset.
	 * 
	 * @return A sample chart.
	 */
	private JFreeChart createChart(final XYDataset dataset) {
		final JFreeChart result = ChartFactory.createTimeSeriesChart(
				"Light Intensity Graph", "Time", "Intensity (cd/m^2)", dataset,
				true, true, false);
		final XYPlot plot = result.getXYPlot();
		ValueAxis axis = plot.getDomainAxis();
		axis.setAutoRange(true);
		axis.setFixedAutoRange(60000.0); // 60 seconds
		axis = plot.getRangeAxis();
		axis.setRange(0.0, 1000.0);
		return result;
	}

	// ****************************************************************************
	// * JFREECHART DEVELOPER GUIDE *
	// * The JFreeChart Developer Guide, written by David Gilbert, is available
	// *
	// * to purchase from Object Refinery Limited: *
	// * *
	// * http://www.object-refinery.com/jfreechart/guide.html *
	// * *
	// * Sales are used to provide funding for the JFreeChart project - please *
	// * support us so that we can continue developing free software. *
	// ****************************************************************************

	/**
	 * Handles a click on the button by adding new (random) data.
	 * 
	 * @param e
	 *            the action event.
	 */
	public static void actionPerformedManual(Double lightValue) {

		if (lightValue > 2)
			locLightValue = lightValue;

		final Millisecond now = new Millisecond();
		System.out.println("Now = " + now.toString() + " y" + locLightValue);
		series.add(new Millisecond(), locLightValue);

	}

	public void actionPerformed(final ActionEvent e) {
		System.out.println("actionPerformed");
		if (e.getActionCommand().equals("SHOW_DATA")) {
			System.out.println("actionPerformed");
		}

	}

	/**
	 * Starting point for the demonstration application.
	 * 
	 * @param args
	 *            ignored.
	 */
	public static void main(final String[] args) {

		Timer timer = new Timer();
		timer.schedule(new UpdateTask(), 0, 500);
		final DynamicDataDemo demo = new DynamicDataDemo(" ");
		demo.pack();
		RefineryUtilities.centerFrameOnScreen(demo);
		demo.setVisible(true);

	}

}
